<?php
/**
 * It runs for hourly tasks.
 * 
 * php -q /path/index-cron.php TaskHourly debug hourly_report
 *
 * LBB Solutions Oy 版权所有 © 2013
 */
class TaskHourlyCommand extends CConsoleCommand {
	
	/**
	 * @param array $args
	 *   1. hourly_report: make hourly report
	 */
	public function run($args) {
		Yii::app()->setTimeZone('Europe/Helsinki');
		
		$debug = strtolower($args[0]);
		if ($debug != 'prod') {
			// set the differnet DB
			Yii::app()->db->setActive(false);
			Yii::app()->db->connectionString = 'mysql:host=localhost;dbname=yamiifi_dev';
		}
		$task_key = strtolower($args[1]);
		
		$local_date = date('Y-m-d', mktime(date('G')-1,0,0, date('m'), date('d')));//last hour for date
		$local_hour = date('G', mktime(date('G')-1,0,0, date('m'), date('d')));//last hour
		
		echo date('Y-m-d H:i:s') . ": Start TaskHourlyCommand for {$local_date} ({$local_hour}): {$task_key}";
		switch ($task_key) {
			case 'hourly_report':
				$this->makeVisitReportHourly($local_date, $local_hour);
				break;
		}
		echo date('Y-m-d H:i:s') . ": End TaskHourlyCommand for {$local_date} ({$local_hour}): {$task_key}";
	}
	
	/**
	 * Make the visit hourly report. (last hour)
	 * @param date $date
	 * @param int $hour
	 */
	public function makeVisitReportHourly($date, $hour) {
		$sql_report = "
			INSERT INTO tbl_visit_report_hourly(id_merchant, local_date, local_hour, visits, amount)
			SELECT id_merchant, DATE(create_time) AS local_date, HOUR(create_time) AS local_hour, COUNT(id) AS visits, SUM(amount) AS amount
			FROM tbl_visit_transaction
			where type=1 AND DATE(create_time)=:local_date AND HOUR(create_time)=:local_hour
			GROUP BY id_merchant";
		$params = array(
			':local_date' => $date,
			':local_hour' => $hour,
		);
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_report);
		$n = $command->execute($params);
		$connection->active = false;
		
		echo "<br />\n{$n} row(s) inserted.<br />\n";
	}
}